import { defineStore } from 'pinia'
import axios from 'axios'
import { useUserStore } from './user'

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatHistory: [],
    currentChat: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async sendMessage(message) {
      this.loading = true
      this.error = null
      
      try {
        const userStore = useUserStore()
        const userId = userStore.user ? userStore.user.id : null
        
        const response = await axios.post('http://localhost:5000/api/chat', {
          user_id: userId,
          message
        })
        
        const aiResponse = response.data.message
        
        // 添加到当前聊天
        const chatItem = {
          user_message: message,
          ai_response: aiResponse,
          created_at: new Date().toISOString()
        }
        
        this.currentChat.push(chatItem)
        
        // 如果用户已登录，也添加到历史记录的末尾
        if (userId) {
          // 添加新的聊天记录到末尾
          this.chatHistory.push({
            id: Date.now(), // 临时ID
            user_id: userId,
            user_message: message,
            ai_response: aiResponse,
            created_at: new Date().toISOString()
          })
        }
        
        return aiResponse
      } catch (error) {
        this.error = '发送消息失败'
        console.error(error)
        return null
      } finally {
        this.loading = false
      }
    },
    
    async fetchChatHistory() {
      this.loading = true
      this.error = null
      
      try {
        const userStore = useUserStore()
        if (!userStore.user) {
          this.chatHistory = []
          return []
        }
        
        const response = await axios.get(`http://localhost:5000/api/chat/history?user_id=${userStore.user.id}`)
        this.chatHistory = response.data.history
        return response.data.history
      } catch (error) {
        this.error = '获取聊天历史失败'
        console.error(error)
        return []
      } finally {
        this.loading = false
      }
    },
    
    clearCurrentChat() {
      this.currentChat = []
    },
    
    // 使用聊天历史初始化当前聊天
    initCurrentChatFromHistory() {
      this.clearCurrentChat()
      
      // 直接使用历史记录，不需要倒序，因为后端已经按时间正序返回
      for (const record of this.chatHistory) {
        this.currentChat.push({
          user_message: record.user_message,
          ai_response: record.ai_response,
          created_at: record.created_at
        })
      }
    }
  }
}) 